package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;

    //用户下单
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders, HttpSession session) {
        log.info("订单数据：{}", orders);
        orderService.submit(orders,session);
        return R.success("下单成功");
    }

    //订单分页查询
    @GetMapping("/userPage")
    public R<Page> userPage(int page, int pageSize) {
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>();

        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Orders::getOrderTime);
        orderService.page(pageInfo, wrapper);

        BeanUtils.copyProperties(pageInfo, ordersDtoPage, "records");

        List<Orders> records = pageInfo.getRecords();
        List<OrdersDto> list = records.stream().map((item -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);

            Long id = item.getId();
            LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(OrderDetail::getOrderId, id);

            int count = orderDetailService.count(queryWrapper);
            List<OrderDetail> orderDetails = orderDetailService.list(queryWrapper);

            ordersDto.setOrderDetails(orderDetails);
            ordersDto.setSumNum(count);

            return ordersDto;
        })).collect(Collectors.toList());

        ordersDtoPage.setRecords(list);
        return R.success(ordersDtoPage);
    }

    //再来一单
    @Transactional
    @PostMapping("/again")
    public R<String> again(@RequestBody Orders orders) {
        Long id = orders.getId();
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId, id);
        List<OrderDetail> list = orderDetailService.list(queryWrapper);


        list.stream().map((item -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setName(item.getName());
            shoppingCart.setImage(item.getImage());
            shoppingCart.setUserId(BaseContext.getCurrentId());

            LambdaQueryWrapper<Dish> dishWrapper = new LambdaQueryWrapper<>();
            dishWrapper.eq(Dish::getId, item.getDishId());
            Dish dish = dishService.getOne(dishWrapper);
            Integer status = dish.getStatus();
            if (status != 1) {
                throw new CustomException("订单中存在已停售的菜品");
            }

            shoppingCart.setDishId(item.getDishId());

            LambdaQueryWrapper<Setmeal> setMealWrapper = new LambdaQueryWrapper<>();
            setMealWrapper.eq(Setmeal::getId, item.getSetmealId());
            Setmeal setmeal = setmealService.getOne(setMealWrapper);
            Integer status2 = setmeal.getStatus();
            if (status != 1) {
                throw new CustomException("订单中存在已停售的套餐");
            }

            shoppingCart.setSetmealId(item.getSetmealId());
            shoppingCart.setDishFlavor(item.getDishFlavor());
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setAmount(item.getAmount());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.save(shoppingCart);

            return item;
        })).collect(Collectors.toList());

        return R.success("添加成功");
    }

    //管理端分页查询
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String number,String beginTime,String endTime) {

        Page<Orders> pageInfo = new Page<>(page, pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>();

        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(number != null, Orders::getId, number);
        wrapper.between(beginTime!=null&&endTime!=null,Orders::getOrderTime,beginTime,endTime);

        wrapper.orderByDesc(Orders::getOrderTime);
        orderService.page(pageInfo, wrapper);

        BeanUtils.copyProperties(pageInfo, ordersDtoPage, "records");

        List<Orders> records = pageInfo.getRecords();
        List<OrdersDto> list = records.stream().map((item -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);
            ordersDto.setUserName(item.getConsignee());
            return ordersDto;
        })).collect(Collectors.toList());

        ordersDtoPage.setRecords(list);
        return R.success(ordersDtoPage);
    }
    //管理端修改状态
    @PutMapping
    public R<String> update(@RequestBody Orders orders) {
        Long id = orders.getId();
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getId, id);
        Orders serviceOne = orderService.getOne(queryWrapper);
        serviceOne.setStatus(orders.getStatus());
        orderService.updateById(serviceOne);
        return R.success("修改成功");
    }
}
